package test.administrator.example.com.mvptest1.framework.support.base;

/**
 * Created by thinkpad on 2018/7/17.
 */

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import test.administrator.example.com.mvptest1.framework.MvpPresenter;
import test.administrator.example.com.mvptest1.framework.MvpView;
import test.administrator.example.com.mvptest1.framework.lce.MvpLceView;

/**
 * 实现具体绑定
 */
public class MvpBasePresenter<V extends MvpView> implements MvpPresenter<V> {

	//TODO 弱引用处理
	private V viewProxy;
	private V view;

	public V getView() {
		return viewProxy;
	}

	@Override
	public void attachView(V view) {
		this.view = view;
		//目标接口->实际上是MvpView
		Class<?>[] interfaces = view.getClass().getInterfaces();
		viewProxy = (V) Proxy.newProxyInstance(view.getClass().getClassLoader(), interfaces, new ProxyInvocationHandler<V>(view));
	}

	@Override
	public void detachView() {
		this.view = null;
	}

	@Override
	public void destroy() {
	}

	private class ProxyInvocationHandler<V extends MvpView> implements InvocationHandler {

		private V view;

		public ProxyInvocationHandler(V view) {
			this.view = view;
		}

		@Override
		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
			if (view != null) {
				//执行
				return method.invoke(view, args);
			}
			//不存在->报错了
			throw new NullPointerException("空指针异常");
//			return null;
		}
	}

}





























